<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="基地名" prop="baseName">
        <el-select
          v-model="queryParams.pid"
          placeholder="请选择基地"
          filterable
           disabled="true"
        >
          <el-option
            v-for="item in placeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="订单id" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入订单id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预订用户姓名" prop="username" label-width="150px">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入预订用户姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预订用户身份证" prop="idcard" label-width="150px">
        <el-input
          v-model="queryParams.idcard"
          placeholder="请输入预订用户身份证"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布人" prop="groupUserName">
        <el-input
          v-model="queryParams.groupUserName"
          placeholder="请输入发布人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['orders:orders:remove2']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['orders:orders:export2']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Plus"
          @click="addCourseScore"
          v-show="!isShow"
          v-hasPermi="['orders:orders:addCourseScore']"
          >对所有签到成功用户添加学分</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-show="isShow"
          type="info"
          plain
          icon="Plus"
          @click="revert"
          v-hasPermi="['orders:orders:revert2']"
          >撤回所有签到成功用户学分添加</el-button
        >
      </el-col>

       <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" @click="changeShowWan" v-show="!isShowWan"
          >调整完成情况</el-button
        >
        <el-button type="danger" @click="changeShowWan" v-show="isShowWan"
          >关闭调整</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="ordersList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单id" align="center" prop="id" width="180px" />
      <el-table-column
        label="预订用户姓名"
        align="center"
        prop="username"
        width="150px"
      />
      <el-table-column
        label="预订用户电话"
        align="center"
        prop="phone"
        width="150px"
      />
      <el-table-column
        label="培训费(元)"
        align="center"
        prop="price"
        width="100px"
      />
      <el-table-column
        label="预订用户身份证"
        align="center"
        prop="idcard"
        width="250px"
      />
      <el-table-column
        label="用户培训签到签退(未完成/已完成)"
        align="center"
        prop="idcard"
        width="250px"
      >
        <template #default="scope">
          <el-switch
            :disabled="!isShowWan"
            @change="changStatus(scope.row)"
            v-model="scope.row.status"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="本次行程主题"
        align="center"
        prop="tripName"
        width="250px"
      />
      <el-table-column
        label="本次行程详情"
        align="center"
        prop="tripContent"
        width="300px"
      />
      <el-table-column
        label="发布人"
        align="center"
        prop="groupUserName"
        width="150px"
      />
      <el-table-column
        label="发布人电话"
        align="center"
        prop="groupPhone"
        width="150px"
      />
      <el-table-column
        label="行程日期"
        align="center"
        prop="startDate"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预约订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ordersRef" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Orders">
import { useStore } from "vuex";
const store = useStore();
const sendMsg = () => {
  for(let item of addOrdersList.value){
    let msgObj = {
      to: item.username,
      content: '您于'+item.baseName+'基地,日期为'+item.startDate+',主题为'+item.tripName+'的签到审核通过，您的培训课时已增加', 
      notSelf: false,
    };
    store.state.stomp.send("/ws/success", {}, JSON.stringify(msgObj));

  }
  
};


 

const isShowWan = ref(false);
function changeShowWan() {
  isShowWan.value = !isShowWan.value;
}

function revert() {
  revertScore(queryParams.value.baseName).then((response) => {
    proxy.$modal.msgSuccess("撤回成功");
    isShow.value = !isShow.value;
  });
}

function addCourseScore() {
  addUserScore(queryParams.value.baseName,uids.value, tids.value).then((response) => {
    proxy.$modal.msgSuccess("对所有完成培训用户学分添加成功");
    sendMsg()
    isShow.value = !isShow.value;
  });
}

function changStatus(row) {
  data.form = row;
  // console.log(data.form.status);
  // data.form.status=data.form.status=="true"?1:0;
  submitForm(); 
}

import { listPlace } from "@/api/place/place";
import { loadAllParams } from "@/api/page";
// 查询基地列表
const placeList = ref([]);

function getPlaceList() {
  listPlace(loadAllParams).then((response) => {
    placeList.value = response.rows;
  });
}
getPlaceList();

import {
  isShowButton,
  listOrders,
  getOrders,
  delOrders,
  addOrders,
  updateOrders,
  addUserScore,
  revertScore,
} from "@/api/orders/orders2";
import { ElMessage } from "element-plus";
import { onMounted } from "vue";

const { proxy } = getCurrentInstance();

const ordersList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeStartDate = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    username: null,
    idcard: null,
    baseName: window.localStorage.getItem("name"),
    groupUserName: null,
    startDate: null,
    pid: Number(window.localStorage.getItem("id")),
    params: {
      beginStartDate: null,
      endStartDate: null,
    },
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}
/** 查询预约订单列表 */
function getList() {
    loading.value = true;
    if (null != daterangeStartDate && "" != daterangeStartDate) {
      queryParams.value.params["beginStartDate"] = formatDate(new Date());
      queryParams.value.params["endStartDate"] = formatDate(new Date());
    }
    listOrders(queryParams.value).then((response) => {
      ordersList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
}
const Params = ref({
  pageNum: 1,
  pageSize: 10000,
  pid: window.localStorage.getItem("id"),
  params: {
    beginStartDate: null,
    endStartDate: null,
  },
});
const uids = ref([]);
const tids = ref([]);
const ordersAllList = ref([]);
const isShow = ref(false);
function isShowButtonMethod() {
  isShowButton(queryParams.value.baseName).then((response) => {
    isShow.value = response;
  });
}
isShowButtonMethod();
const addOrdersList=ref([])
function getAllList() {

    Params.value.params["beginStartDate"] = formatDate(new Date());
    Params.value.params["endStartDate"] = formatDate(new Date());
    listOrders(Params.value).then((response) => {
      if (response.code == 200) ordersAllList.value = response.rows;
       addOrdersList.value = ordersAllList.value
        .filter((item) => item.status === true)
     
      uids.value = ordersAllList.value
        .filter((item) => item.status === true)
        .map((item) => item.uid);
      tids.value = ordersAllList.value
        .filter((item) => item.status === true)
        .map((item) => item.studyCourse);
      console.log(uids.value, tids.value);
    });
}
getAllList()
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    username: null,
    phone: null,
    price: null,
    idcard: null,
    gmtPayment: null,
    aliPaytradeNo: null,
    baseName: null,
    tripName: null,
    tripContent: null,
    groupUserName: null,
    groupPhone: null,
    uid: null,
    startDate: null,
  };
  proxy.resetForm("ordersRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeStartDate.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加预约订单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getOrders(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改预约订单";
  });
}

/** 提交按钮 */
function submitForm() {
  if (form.value.id != null) {
    updateOrders(form.value).then((response) => {
      proxy.$modal.msgSuccess("修改成功");
      getAllList();
      open.value = false;
      getList();
    });
  } else {
    addOrders(form.value).then((response) => {
      proxy.$modal.msgSuccess("新增成功");
      open.value = false;
      getList();
    });
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除预约订单编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delOrders(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "orders/orders/export",
    {
      ...queryParams.value,
    },
    `orders_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
